package com.kobeliu.api.interceptor;

import com.google.gson.Gson;
import com.kobeliu.base.BaseInfoProperties;
import com.kobeliu.pojo.Admin;
import com.kobeliu.pojo.Users;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class JwtCurrentUserInterceptor extends BaseInfoProperties implements HandlerInterceptor {

    public static ThreadLocal<Users> currentUser = new ThreadLocal<>();
    public static ThreadLocal<Admin> currentAdmin = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //ThreadLocal同一线程同步数据
        // 流程：interceptor --> 控制器 --> 业务层
        //request的header中获取数据、
//        log.info("经过过滤器了============================================");
        String appUserJson = request.getHeader(APP_USER_JSON);
        String adminUserJson = request.getHeader(ADMIN_USER_JSON);
        String saasUserJson = request.getHeader(SAAS_USER_JSON);

//        log.info("admin:{}",adminUserJson);
//        log.info("=====================================================");

        if(StringUtils.isNotBlank(appUserJson)){
            Users appUser = new Gson().fromJson(appUserJson, Users.class);
            currentUser.set(appUser);
        } else if(StringUtils.isNotBlank(saasUserJson)){
            Users saasUser = new Gson().fromJson(saasUserJson, Users.class);
            currentUser.set(saasUser);
        } else {
            Admin adminUser = new Gson().fromJson(adminUserJson, Admin.class);
            currentAdmin.set(adminUser);
        }

//        Admin adminUser = new Gson().fromJson(adminUserJson, Admin.class);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        currentAdmin.remove();
        currentUser.remove();
    }
}
